#include <my_header.h>
// B可连续发送 A也可连续接受
// 并加入超时设置
/* Usage: ./1_BUser_select */
int main(int argc, char *argv[]){                                  
    int fd_read = open("write.pipe", O_RDONLY);
    int fd_write = open("read.pipe", O_WRONLY);
    ERROR_CHECK(fd_read, -1, "open read");
    ERROR_CHECK(fd_write, -1, "open write");
    printf("管道打开！\n");
    // 作为交换数据中间件的缓冲区
    char buf[60];
    // 装文件描述符结构体
    fd_set set; 
    while(1)
    {
        // 初始化
        FD_ZERO(&set);
        // 监听文件描述符
        FD_SET(STDIN_FILENO, &set);
        FD_SET(fd_read, &set);
        
        struct timeval time_val;
        time_val.tv_sec = 10;//10s
        time_val.tv_usec = 0;

        int res_select = select(10, &set, NULL, NULL,
                                &time_val);
        ERROR_CHECK(res_select, -1, "select");
        // 打印剩余时间
        printf("tv_sec:%ld\n", time_val.tv_sec);
        if(FD_ISSET(fd_read, &set))
        {
            bzero(buf, sizeof(buf));
            int read_num = read(fd_read, buf, sizeof(buf));
            if(read_num == 0)
            {
                printf("对方已断开连接\n");
                break;
            }
            printf("UserB: %s", buf);
        }

        if(FD_ISSET(STDIN_FILENO, &set))
        {
            bzero(buf, sizeof(buf));
            int read_num = read(STDIN_FILENO, buf, sizeof(buf));
            if(read_num == 0)
            {
                break;  //ctrl+d,终止标准输入
            }
             write(fd_write, buf, sizeof(buf));

        }
    }

    close(fd_read);
    close(fd_write);
    return 0;
}


